package com.googlecode.continuity.plugin.gwtext.client;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;

/**
 * CenteredDialogBox
 *
 * @author Peter Schmitt <aragos@aragos.de>
 */
public abstract class CenteredDialogBox extends DialogBox {
  protected boolean positioned;
  protected VerticalPanel frame;
  protected HorizontalPanel buttons;
  protected ClickListener finished;

  public CenteredDialogBox() {
    super(false, true);
    frame = new VerticalPanel();
    buttons = new HorizontalPanel();
    frame.add(buttons);
    positioned = false;
    finished = new ClickListener() {
      public void onClick(Widget sender) {
        hide();
      }
    };
    setWidget(frame);
    addStyleName("centeredDialog");
    buttons.addStyleName("buttons");
  }

  /**
   * Shows the confirm box and centers it in the client window.
   */
  public void show() {
    if (!positioned) {
      positioned = true;
      setPopupPositionAndShow(new PositionCallback() {
        public void setPosition(int offsetWidth, int offsetHeight) {
          // center popup
          setPopupPosition(Math.round((Window.getClientWidth() - offsetWidth) / 2) + Window.getScrollLeft(),
              Math.round((Window.getClientHeight() - offsetHeight) / 3) + Window.getScrollTop());
        }
      });
    } else {
      positioned = false;
      super.show();
    }
  }

  // hide box on escape pressed
  public boolean onEventPreview(Event event) {
    if (DOM.eventGetType(event) == Event.ONKEYDOWN && DOM.eventGetKeyCode(event) == 27) {
      hide();
      return false;
    }
    return super.onEventPreview(event);
  }
}
